{extend name="common/base"}
{block name="css"}
{__block__}
<style>
    .filter-item {
        padding-top: 2px;
        padding-bottom: 2px;
    }

    #more-filter {
        display: none;
    }
</style>
{/block}
{block name="content"}
<table id="filter" lay-filter="filter">
    <tr>
        <td width="60">
            <span class="layui-badge layui-bg-gray" style="font-size: 10px;height: 30px; line-height: 15px;padding: 5px 10px;"><i class="layui-icon">&#xe615;</i><br>筛选</span>
        </td>
        <td>
            <form class="layui-form  layui-form-pane">
                <div class="layui-inline filter-item">
                    <label class="layui-form-label">名称</label>
                    <div class="layui-input-inline">
                        <select name="contract[name]" lay-filter="name" lay-search>
                            <option value></option>
                            {volist name="contracts" id="contract"}
                            <option value="{$contract.name}">{$contract.name}</option>
                            {/volist}
                        </select>
                    </div>
                </div>
                <div class="layui-inline filter-item">
                    <label class="layui-form-label">编号</label>
                    <div class="layui-input-inline">
                        <!--
                        <select name="contract[contract_sn]" lay-filter="contract_sn" lay-search>
                            <option value></option>
                            {volist name="contracts" id="contract"}
                            <option value="{$contract.contract_sn}">{$contract.contract_sn}</option>
                            {/volist}
                        </select>
                        -->
                        <div class="layui-input-inline">
                            <input type="text" name="contract[contract_sn]" placeholder="合同编号" autocomplete="off"
                                   class="layui-input">
                        </div>
                    </div>
                </div>
                <div class="layui-inline filter-item">
                    <label class="layui-form-label">客户</label>
                    <div class="layui-input-inline">
                        <select name="customer[id]" lay-filter="customer" lay-search>
                            <option value></option>
                            {volist name="customers" id="customer"}
                            <option value="{$customer.id}">{$customer.name}</option>
                            {/volist}
                        </select>
                    </div>
                </div>
                <span id="more-filter">
                <div class="layui-inline filter-item">
                    <label class="layui-form-label">状态</label>
                    <div class="layui-input-inline">
                        <select name="contract[status]" lay-filter="status" lay-search>
                            <option value></option>
                            <option value="0">新录</option>
                            <option value="1">待审</option>
                            <option value="2">审批中</option>
                            <option value="3">驳回</option>
                            <option value="4">过审</option>
                            <option value="5">执行中</option>
                            <option value="6">中止</option>
                            <option value="7">续期</option>
                            <option value="8">完成</option>
                        </select>
                    </div>
                </div>
                <div class="layui-inline filter-item">
                    <label class="layui-form-label">类别</label>
                    <div class="layui-input-inline">
                        <select name="category[id]" lay-filter="category" lay-search>
                            <option value></option>
                            {volist name="categories" id="category"}
                            <option value="{$category.id}">{$category.name}</option>
                            {/volist}
                        </select>
                    </div>
                </div>
                <div class="layui-inline filter-item">
                    <label class="layui-form-label">类型</label>
                    <div class="layui-input-inline">
                        <select name="type[id]" lay-filter="type" lay-search>
                            <option value></option>
                            {volist name="types" id="type"}
                            <option value="{$type.id}">{$type.name}</option>
                            {/volist}
                        </select>
                    </div>
                </div>
                <div class="layui-inline filter-item">
                    <label class="layui-form-label">负责人</label>
                    <div class="layui-input-inline">
                        <input type="text" name="manager[name]" placeholder="负责人姓名" autocomplete="off"
                               class="layui-input">
                    </div>
                </div>
                <div class="layui-inline filter-item">
                    <label class="layui-form-label">签约日</label>
                    <div class="layui-input-inline">
                        <input type="text" name="contract_date[start]" autocomplete="off"
                               class="layui-input" id="contract_date_start">
                    </div>
                    -
                    <div class="layui-input-inline">
                        <input type="text" name="contract_date[end]" autocomplete="off"
                               class="layui-input" id="contract_date_end">
                    </div>
                </div>
                <div class="layui-inline filter-item">
                    <label class="layui-form-label">到期日</label>
                    <div class="layui-input-inline">
                        <input type="text" name="due_date[start]" autocomplete="off"
                               class="layui-input" id="due_date_start">
                    </div>
                    -
                    <div class="layui-input-inline">
                        <input type="text" name="due_date[end]" autocomplete="off"
                               class="layui-input" id="due_date_end">
                    </div>
                </div>

                </span>
                <a class="layui-btn" id="more-btn">高级</a>
                <button class="layui-btn" lay-submit lay-filter="search">搜索</button>
            </form>
        </td>
    </tr>
</table>
<table id="contract" lay-filter="contract"></table>
<script type="text/html" id="operateBar">
    <a class="layui-btn layui-btn-xs" lay-event="detail">查看</a>
    {// 新录与驳回的合同才能编辑if(d.status == 3 || d.status == 0) }
    <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
    {// 新录与驳回的合同，并且只有超级管理员才能删除 if((d.status == 3 || d.status == 0) && '$Think.session.admin.level'==1) }
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
    <!-- 这里同样支持 laytpl 语法，如： -->
    {{#  if(d.auth > 2){ }}
    <a class="layui-btn layui-btn-xs" lay-event="check">审核</a>
    {{#  } }}
</script>

{// 审批状态 }
<script type="text/html" id="nameTpl">
    {{d.name}}
    {{# if(d.approval) { }}
        {{#
            var iconColor='';
            if(d.approval.start==2) {
                d.status = '锁定';
                iconColor='#393D49'
            } else {
                var process = Math.floor(d.approval.process / d.approval.total_nodes * 100);
                if(process>100) process=100;
                process += '%';
                d.status = '审批进度 ' + process;
                iconColor='#FFB800';
            }
            if(d.approval.status==2) {d.status+=' <span class="layui-badge layui-bg-orange">审核通过</span>';iconColor='#5FB878'}
            if(d.approval.status==3) {d.status+=' <span class="layui-badge">审核驳回</span>';iconColor='#FF5722'}

    }}

        <span class="icon icon-flow hasApproval" style="color:{{iconColor}}" data-name="{{d.approval.name}}" data-status='{{d.status}}'></span>
    {{# } }}
</script>
<script type="text/html" id="statusTpl">
    {{#
        var contractStatus = {
            0: "新录",
            1: "待审",
            2: "审批中",
            3: "驳回",
            4: "过审",
            5: "执行",
            6: "中止",
            7: "已续期",
            8: "完成"
        };
    }}
    {{ contractStatus[d.status] }}
</script>
{/block}

{block name="js"}
{__block__}
<script>
    layui.use(['form', 'table','laydate'], function () {
        var $ = layui.jquery;
        var table = layui.table;
        var form = layui.form;
        var laydate = layui.laydate;
        // date
        laydate.render({
            elem: '#contract_date_start' //指定元素
        });
        laydate.render({
            elem: '#contract_date_end' //指定元素
        });
        laydate.render({
            elem: '#due_date_start' //指定元素
        });
        laydate.render({
            elem: '#due_date_end' //指定元素
        });
        // filter
        // more toggle
        $('#more-btn').click(function () {
            var moreFilter = $('#more-filter');
            var moreBtn = $('#more-btn');
            if ((moreFilter.css('display')) === 'none') {
                moreFilter.show();
                moreBtn.html('简洁');
            } else {
                moreFilter.hide();
                moreBtn.html('高级');
            }
        });
        // 使用contract name or sn筛选时， 禁用其他条件
        var changeFn = function (data) {
            if (data.value) {
                $('.filter-item select, .filter-item input').not(data.elem).attr("disabled","disabled");
                layer.msg('其他条件已禁用');
            } else {
                $('.filter-item select, .filter-item input').not(data.elem).removeAttr("disabled");
                layer.msg('其他条件已启用');
            }
            form.render('select');
        }
        form.on('select(name)', changeFn);
        form.on('select(contract_sn)', changeFn);
        // 监听category select
        var category = null;
        form.on('select(category)', function (data) {
            // console.log(data.value);
            // console.log(data.elem);
            category = $(data.elem);
            $.get({
                url: '/type/getByCategoryId/' + data.value,
                success: function (result) {
                    if (result == -1) {
                        layer.msg('非法操作');
                    } else {
                        var options = '<option value></option>';
                        for (var i in result) {
                            options += '<option value="' + result[i]['id'] + '" data-sn="' + result[i]['sn'] + '">' + result[i]['name'] + '</option>'
                        }
                        console.log(options);
                        $('select[name="type[id]"]').empty().append(options);
                        form.render('select');
                    }
                },
                fail: function (error) {
                    console.log(error);
                }
            });
        });

        // filter submit
        form.on('submit(search)', function (data) {
            console.log(data.field);
            // 判断筛选条件是否为空
            var selectHasVal = false;
            $('.filter-item select').each(function () {
                if ($(this).val()) {
                    selectHasVal = true;
                    return;
                }
            })
            if (!selectHasVal) {
                $('.filter-item input').each(function () {
                    if ($(this).val()) {
                        selectHasVal = true;
                        return;
                    }
                })
            }
            if (!selectHasVal) {
                layer.msg('没有设置筛选条件');
                return false;
            }
            // 发送筛选请求
            var fileterIndex = layer.load(1);
            $.post({
                url: '/contract/search',
                data: data.field,
                success: function (result) {
                    console.log(result)
                    layer.close(fileterIndex);
                    layer.msg('筛选完成');
                    tableIns.reload({
                        data: result,
                        page: {
                            curr: 1
                        }
                    });
                },
                fail: function (error) {
                    layer.close(fileterIndex);
                    console.log(error)
                    layer.open({
                        content: '网络错误或服务器内部错误，请重试'
                    })
                }
            })
            return false;
        });

        // 渲染表格

        var tableIns = table.render({
            elem: '#contract'
            , height: 'full-270'
            , data: {$contracts}
            , page: true //开启分页
            , limit: 15
            , cols: [[ //表头
                {checkbox: true},
                {title: '序号', width: 80, templet: '<div>{{d.LAY_INDEX}}</div>', sort: true}
                , {field: 'contract_sn', title: '合同编号', sort: true}
                , {field: 'name', title: '合同标题',/* templet: '#nameTpl',*/ sort: true}
                , {field: 'type', title: '合同类型', width:120, templet: '<div>{{d.type.name}}</div>', sort: true}
                , {field: 'manager', title: '负责人', width: 100, sort: true}
                , {
                    field: 'due_date',
                    title: '签约日',
                    width: 100,
                    templet: '<div>{{new Date(d.contract_date * 1000).toLocaleDateString()}}</div>',
                    sort: true
                }
                , {
                    field: 'due_date',
                    title: '到期日',
                    width: 100,
                    templet: '<div>{{new Date(d.due_date * 1000).toLocaleDateString()}}</div>',
                    sort: true
                }
                ,{field: 'status', title: '状态', width:80, templet: '#statusTpl', sort: true}
                , {title: '操作', fixed: 'right', width: 150, align: 'left', toolbar: '#operateBar'}
            ]]
        });
        // 表格工具条操作
        table.on('tool(contract)', function (obj) { //注：tool是工具条事件名，test是table原始容器的属性 lay-filter="对应的值"
            var data = obj.data; //获得当前行数据
            var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
            var tr = obj.tr; //获得当前行 tr 的DOM对象
            console.log(data);
            // 删除
            if (layEvent === 'del') {
                layer.confirm('确定要删除吗', {icon: 3, title: '提示'}, function (index) {
                    var delLoadingIndex = layer.load(1);
                    $.ajax({
                        type: 'DELETE',
                        url: '/contract/del/' + data.id,
                        success: function (result) {
                            layer.close(delLoadingIndex);
                            if (result === 1) {
                                obj.del();
                                layer.msg('操作成功');
                                console.log(result);
                            } else if (result === 'hasApproval') {
                                layer.open({title: '警告', content: '当前合同已关联审批，请先删除该合同的关联审批，再进行该操作！', icon: 2})
                            } else {
                                layer.msg('操作失败 ' + result);
                                console.log(result);
                            }
                        },
                        error: function (error) {
                            layer.close(delLoadingIndex);
                            layer.msg('操作失败');
                            console.log(error)
                        }
                    });

                    layer.close(index);
                });
            }
            // 编辑
            if (layEvent === 'edit') {
                location.href = '/contract/edit/' + data.id;
            }

            // 查看详情
            if (layEvent === 'detail') {
                var dueDays = '';
                if (data.days) {
                    dueDays = '<span class="layui-badge" style="margin-left: 15px;">' + data.days + '天后过期</span>';
                }
                var content = '<div style="padding: 10px;">' +
                    '<table class="layui-table">' +
                    '<tr><th style="font-weight: bold;" width="80">ID</th><td>' + data.id + '</td></tr>' +
                    '<tr><th style="font-weight: bold;">合同编号</th><td>' + data.contract_sn + '</td></tr>' +
                    '<tr><th style="font-weight: bold;">合同名称</th><td>' + data.name + '</td></tr>' +
                    '<tr><th style="font-weight: bold;">签约日</th><td>' + new Date(data.contract_date * 1000).toLocaleDateString() + '</td></tr>' +
                    '<tr><th style="font-weight: bold;">到期日</th><td>' + new Date(data.due_date * 1000).toLocaleDateString() + dueDays + '</td></tr>' +
                    '<tr><th style="font-weight: bold;">客户名称</th><td>' + data.customer.name + '</td></tr>' +
                    '<tr><th style="font-weight: bold;">客户联系人</th><td>' + data.linkman.name + ' ' + data.linkman.phone + '</td></tr>' +
                    '<tr><th style="font-weight: bold;">备注</th><td>' + data.note + '</td></tr>' +
                    '<tr><th style="font-weight: bold;">合同负责人</th><td>' + data.manager + '</td></tr>' +
                    '<tr><th style="font-weight: bold;">合同所属部门</th><td>' + data.department + '</td></tr>';
                if (data.extra.length > 0) {
                    for (var i in data.extra) {
                        content += '<tr><th style="font-weight: bold;">' + data.extra[i]['title'] + '</th><td>' + data.extra[i]['content'] + '</td></tr>';
                    }
                }
                if (data.file) {
                    content += '<tr><th style="font-weight: bold;">附件</th><td><a href="/uploads/' + data.file.src + '" type="button" class="layui-btn">\n' +
                        '                    <i class="layui-icon">&#xe67c;</i>' + data.file.title + '\n' +
                        '                </a></td></tr>';
                }
                content += '<tr><th style="font-weight: bold;">创建时间</th><td>' + data.create_time + '</td></tr>' +
                    '</table>' +
                    '</div>';
                // 根据合同状态设置按钮与回调
                var detailBtn = '确定';
                // 新录
                if (data.status == 0) {
                    detailBtn = ['确定', '立即执行'];
                    var detailBtn2 = function (index1, layero) {
                        layer.confirm('确定不需要审核，立即执行吗？', function (index2) {
                            $.post({
                                url: '/contract/execute/'+data.id,
                                success: function (result) {
                                    if (result === 1) {
                                        layer.msg('执行成功');
                                        layer.close(index2);
                                        location.reload();
                                    } else {
                                        layer.msg('执行失败', {icon: 3})
                                    }
                                },
                                fail: function (error) {
                                    console.log(error)
                                    layer.msg('执行失败', {icon: 3});
                                }
                            })
                        });
                        return false;
                    }
                }
                // 中止
                if (data.status == 6) {
                    detailBtn = ['确定', '恢复执行'];
                    var detailBtn2 = function (index1, layero) {
                        layer.confirm('确定恢复执行该合同吗？', function (index2) {
                            $.post({
                                url: '/contract/execute/'+data.id,
                                success: function (result) {
                                    if (result === 1) {
                                        layer.msg('恢复成功');
                                        layer.close(index2);
                                        location.reload();
                                    } else {
                                        layer.msg('恢复失败', {icon: 3})
                                    }
                                },
                                fail: function (error) {
                                    console.log(error)
                                    layer.msg('恢复失败', {icon: 3});
                                }
                            })
                        })
                        return false;
                    }
                }
                // 执行中
                if (data.status == 5) {

                    detailBtn = ['确定', '中止', '已续期','已完成'];

                    var detailBtn2 = function (index1, layero) {
                        layer.confirm('确定要中止合同吗？', function (index2) {
                            $.post({
                                url: '/contract/cancel/'+data.id,
                                success: function (result) {
                                    if (result === 1) {
                                        layer.msg('中止操作成功',{time:3}, function () {
                                            layer.close(index2);
                                            location.reload();
                                        });
                                    } else {
                                        layer.msg('中止操作失败', {icon: 3})
                                    }
                                },
                                fail: function (error) {
                                    console.log(error)
                                    layer.msg('中止操作失败', {icon: 3});
                                }
                            })
                        })
                        return false;
                    }
                    var detailBtn3 = function (index1, layero) {
                        layer.confirm('确定要将该合同设置为已续期吗？', function (index2) {
                            $.post({
                                url: '/contract/renew/'+data.id,
                                success: function (result) {
                                    if (result === 1) {
                                        layer.msg('设置成功');
                                        layer.close(index2);
                                        location.reload();
                                    } else {
                                        layer.msg('设置失败', {icon: 3})
                                    }
                                },
                                fail: function (error) {
                                    console.log(error)
                                    layer.msg('设置失败', {icon: 3});
                                }
                            })
                        })
                        return false;
                    }
                    var detailBtn4 = function (index1, layero) {
                        layer.confirm('确定要将该合同设置为完成吗？', function (index2) {
                            $.post({
                                url: '/contract/finish/'+data.id,
                                success: function (result) {
                                    if (result === 1) {
                                        layer.msg('设置成功');
                                        layer.close(index2);
                                        location.reload();
                                    } else {
                                        layer.msg('设置失败', {icon: 3})
                                    }
                                },
                                fail: function (error) {
                                    console.log(error)
                                    layer.msg('设置失败', {icon: 3});
                                }
                            })
                        })
                        return false;
                    }
                }

                var index = layer.open({
                    type: 1,
                    area: ['500px'],
                    maxmin: true,
                    btn: detailBtn,
                    btnAlign: 'c',
                    title: '合同详情',
                    content: content, //这里content是一个普通的String
                    btn2: detailBtn2,
                    btn3: detailBtn3,
                    btn4: detailBtn4
                });
            }
        })

        // tips
        var tipsIndex = null;
        $('.hasApproval').hover(function () {
            var that = this;
            var msg = '已关联审批<br><b>'+$(that).data('name')+'</b><br>'+$(that).data('status');
            tipsIndex = layer.tips(msg, that,{tips: [2,'#5FB878'],time: 0});
        },function(){
            layer.close(tipsIndex);
        })
    })
</script>
{/block}